<template>
  <el-form :model="ocean" :rules="rules" ref="ocean" label-width="100px" class="demo-ocean" enctype="multipart/form-data">
    <el-form-item label="海洋名称" prop="ocean_name">
      <el-input v-model="ocean.ocean_name" maxlength="20" show-word-limit name="ocean_name"></el-input>
    </el-form-item>
    <el-form-item label="海洋描述" prop="description">
      <el-input type="textarea" v-model="ocean.description" :autosize="{ minRows: 3, maxRows: 3 }" resize="none" name="description"></el-input>
    </el-form-item>
    <el-form-item label="海洋详情" prop="detail">
      <article-editor ref="editor" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm('ocean')">立即添加</el-button>
      <el-button @click="resetForm('ocean')">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
  import { addOcean } from 'network/ocean'

  import ArticleEditor from 'components/articleEditor/ArticleEditor'

  export default {
    name: 'Add',
    components: { ArticleEditor },
    data() {
      return {
        ocean: {
          ocean_name: '',
          description: ''
        },
        raw: [],
        rules: {
          ocean_name: [
            { required: true, message: '请输入海洋名称', trigger: 'blur' },
            { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
          ],
          description: [
            { required: true, message: '请输入海洋描述', trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      // 提交表单
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            // 获取富文本编辑器内输入的文章内容
            let detail = this.$refs['editor'].editor.getHtml()
            // 判断内容是否为空，为空则输出错误信息
            if (detail) return this.$message({
              type: 'error',
              message: '请输入海洋详情！'
            })
            let formData = new FormData()
            formData.append('ocean_name', this.ocean.ocean_name)
            formData.append('description', this.ocean.description)
            formData.append('detail', detail)
            // 调用添加海洋信息接口
            addOcean(formData).then(res => {
              if (res.status === 1) {
                return this.$message({
                  type: 'error',
                  message: res.message
                })
              }
              this.$message({
                type: 'success',
                message: '添加海洋信息成功！'
              })
              // 清空表单
              this.resetForm(formName)
            })
          } else {
            this.$message({
              type: 'error',
              message: '请输入完整且正确的信息！'
            })
            return false;
          }
        })
      },

      // 重置表单
      resetForm(formName) {
        // 清空表单
        this.$refs[formName].resetFields()
        // 清空编辑器
        this.$refs['editor'].editor.clear()
      }
    }
  }
</script>

<style scoped>
  .el-form {
    width: 1200px;
  }
</style>